#include "worker.h"
#include "taskQueue.h"
#include "threadPool.h"
#include "path.h"
#include "password.h"
#include "func.h"
int tidArrInit(tidArr_t * ptidArr, int workerNum){
    // 申请内存 存储每个子线程的tid
    ptidArr->arr = (pthread_t *)calloc(workerNum,sizeof(pthread_t));
    ptidArr->workerNum = workerNum;
    return 0;
}
void unlock(void *arg){
    threadPool_t * pthreadPool = (threadPool_t *)arg;
    printf("unlock!\n");
    pthread_mutex_unlock(&pthreadPool->mutex);
}
void * threadFunc(void *arg){
    threadPool_t * pthreadPool = (threadPool_t *)arg;
    pathStack_t pathStack;
    while(1){
        pthread_mutex_lock(&pthreadPool->mutex);
        int netfd;
        //pthread_cleanup_push(unlock,pthreadPool);
        while(pthreadPool->exitFlag == 0 && pthreadPool->taskQueue.queueSize <= 0){
            pthread_cond_wait(&pthreadPool->cond, &pthreadPool->mutex);
        }
        if(pthreadPool->exitFlag == 1){
            printf("I am child, I am going to exit!\n");
            pthread_mutex_unlock(&pthreadPool->mutex);
            pthread_exit(NULL);
        }
        //Todo
        //此处定义一个结构体接受出队资源
        netfd = pthreadPool->taskQueue.pFront->netfd;
        printf("I am worker, I got a netfd = %d\n", netfd);
        deQueue(&pthreadPool->taskQueue);
        MYSQL * mysql=mysql_init(NULL);
        MYSQL* cret = mysql_real_connect(mysql,"localhost","root","470868","54th",0,NULL,0);
        if(cret == NULL){
            fprintf(stderr,"mysql_real_connect:%s\n", mysql_error(mysql));
        }

        pthread_mutex_unlock(&pthreadPool->mutex);
        //pthread_cleanup_pop(1);
        // 执行业务
        char path[256] = {0};
        strcat(path,"/home/54th/netdisk3rd");
       int ret= chdir(path);
       ERROR_CHECK(ret,-1,"chdir");
        //Todo，首次连接后判断登录还是注册
        
        train_t train;
        bzero(&train,sizeof(train_t));
        recv(netfd,&train,sizeof(train_t),MSG_WAITALL);
        cmd_t recvcmd;
        bzero(&recvcmd,sizeof(cmd_t));
        memcpy(&recvcmd,train.data,sizeof(cmd_t));
       
        pathStack_t pathStack;
        printf("flag =%d\n",train.flag);
        if(train.flag == TRAIN_LOGIN)
        {
           printf("i am entering login \n");
            login(&pathStack,&recvcmd,mysql,netfd);
        }

        else if(train.flag == TRAIN_SIGN){
        //分支2：首次连接后若为注册
        //分支2逻辑：将train.data解析为cmd,将cmd传递给解注册函数，若注册成功跳出循环执行后续逻辑
           printf("i am entering userRegister\n");
           userRegister(netfd,&recvcmd,mysql);
         

        }
        
        while(1){
          int ret=  parsingCommand(netfd,&pathStack,path,mysql);
          if(ret ==2){
              printf("del user\n");
              break;
          }
          if(ret==1 || ret ==-1){
              printf("quit or client is offline\n");
              close(netfd);
              break;
          }
        }
    }
}
